package org.demo.blog.service.impl;

import org.demo.base.auth.domain.SysUser;
import org.demo.base.file.domain.SysFile;
import org.demo.base.mvc.PageQuery;
import org.demo.base.mvc.PageResult;
import org.demo.base.util.LoginHelper;
import org.demo.blog.domain.Article;
import org.demo.blog.mapper.ArticleMapper;
import org.demo.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @author tomdog
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 发布文章
     * @param article
     */
    @Override
    public void publish(Article article) {
        // 取当前登录人的id和姓名
        SysUser loginUser = LoginHelper.currentLoginUser();
        article.setCreatorId(loginUser.getId());
        article.setCreatorName(loginUser.getNickName());

        article.setCategory("默认");// 默认分组
        article.setStatus(1);// 状态正常
        article.setCreateTime(LocalDateTime.now());// 发布时间为现在
        // 简介取前20个字
        article.setDesc(
            article.getContent().substring(0, article.getContent().length()>20? 20: article.getContent().length()-1)
        );
        // 保存数据
        articleMapper.insert(article);
    }

    @Override
    public List<Article> listAll() {
        // 不是调用的自己写的实现类，而是调用mybatis生成的实现类（根据xml）
        return articleMapper.listAll();
    }

    /**
     * 分页查询
     * @param pageQuery
     * @return
     */
    @Override
    public PageResult<Article> selectPage(PageQuery pageQuery) {
        // total count sql查数据库
        Long total = articleMapper.countAll();
        // data 分页sql查数据库
        List<Article> data = Collections.emptyList();
        if(total>0) {
            data = articleMapper.selectPage(pageQuery);
        }
        // pageNum、pageSize 从pageQuery取
        return PageResult.<Article>builder()
                .data(data)
                .total(total)
                .pageNum(pageQuery.getPageNum())
                .pageSize(pageQuery.getPageSize())
                .build();
    }

    /**
     * 修改图片地址
     */
    @Override
    public void updateImg(Long articleId, String imgPath) {
        articleMapper.updateImg(articleId, imgPath);
    }
}
